//
//  AppDelegate.m
//  SqliteManagerDemo
//
//  Created by US bike on 2017/9/4.
//  Copyright © 2017年 US bike. All rights reserved.
//

#import "AppDelegate.h"
#import "KiwipenRecord.h"
#import "InputDeviceIDViewController.h"
#import <AVFoundation/AVFoundation.h>

#import <GCDWebServer/GCDWebServer-umbrella.h>

@interface AppDelegate ()

@property (nonatomic, strong) AVAudioSession *session;//全局单例，用的时候都给它赋值
@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, strong) AVAudioPlayer *player;//播放器
@property (nonatomic, strong) NSURL *recordFileUrl;

@property (nonatomic, strong) GCDWebServer *webServer;

@property (nonatomic, strong) GCDWebUploader *uploadServer;

@property (nonatomic, strong) GCDWebDAVServer *uploadDAVServer;



@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    /*
    self.webServer = [[GCDWebServer alloc] init];
    
    [self.webServer addDefaultHandlerForMethod:@"GET" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerRequest * _Nonnull request) {
        
        return [GCDWebServerDataResponse responseWithHTML:@"<html><body><p>Hello World</p></body></html>"];
        
    }];
    
    [self.webServer startWithPort:8080 bonjourName:nil];
    */
    
    /*
    NSString *serverPath = [[[[DDFileLogger alloc] init] logFileManager] logsDirectory];
    self.uploadServer = [[GCDWebUploader alloc] initWithUploadDirectory:[[fileLogger logFileManager] logsDirectory]];
    [self.uploadServer start];
    */
    
    /*
    [GCDWebDAVServer setLogLevel:2];
    NSString *serverPath = [[[[DDFileLogger alloc] init] logFileManager] logsDirectory];
    self.uploadDAVServer = [[GCDWebDAVServer alloc] initWithUploadDirectory:serverPath];
    
    
    [self.uploadDAVServer start];
     */
    
    /*
    //处理接收到的奇译笔长按上键事件，开始录音,并保存一段对方的录音文件，显示、保存一段对方的文字,文字准备写入对话框view显示在页面上
        NSLog(@"开始录音");
        //创建avaudiosession单例对象
        AVAudioSession *session = [AVAudioSession sharedInstance];
        //链式,先定义
        NSError *sessionError;
        //设置类别
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if (!session) {
            //NSLog方法其实是封装了description方法， %@ 就是打印 对象 的 descirption方法返回的值
            NSLog(@"创建session失败，原因：%@",[sessionError description]);
        } else {
            //激活,解除激活状态后恢复别的app的激活状态
            [session setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
        }
        self.session = session;
        
        //获取本地沙盒路径
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [path stringByAppendingString:@"/OtherSide.wav"];
        //获取文件路径
        self.recordFileUrl = [NSURL fileURLWithPath:filePath];
    
    
        //设置参数
        NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                       //采样率
                                       [NSNumber numberWithFloat:16000.0f],AVSampleRateKey,
                                       //音频格式
                                       [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
                                       //采样位数
                                       [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                       //音频通道数
                                       [NSNumber numberWithInt:1],AVNumberOfChannelsKey,
                                       //录音质量
                                       [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
                                       nil];
        self.recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:nil];
        
        if (!self.recorder) {
            NSLog(@"无法初始化recorder");
        } else {
            self.recorder.meteringEnabled = YES;
            [self.recorder prepareToRecord];
            //开始录音
            [self.recorder record];
        }

    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"停止录音");
        //停止recorder
        if ([self.recorder isRecording]) {
            [self.recorder stop];
            
            NSData *videoData = [NSData dataWithContentsOfURL:self.recordFileUrl];
            videoData = [KiwipenRecord addHeaderSign:videoData];

            [videoData writeToURL:self.recordFileUrl atomically:YES];
            
        }
        
        NSLog(@"播放录音");
        [self.recorder stop];
        if ([self.player isPlaying]) {
            return;
        }
        self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:self.recordFileUrl error:nil];
        [self.session setCategory:AVAudioSessionCategoryPlayback error:nil];
        [self.player play];

    });

    */
    
    //NSString *path = [[NSBundle mainBundle] pathForResource:@"zh-CN" ofType:@"wav"];
    //NSData *data = [NSData dataWithContentsOfFile:path];
    
    
    //获取本地沙盒路径
    
    InputDeviceIDViewController *inputVC = [InputDeviceIDViewController new];
    
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:inputVC];
    nav.navigationBar.translucent = NO;
    
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    
    
    
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
